<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleClose"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form">
        <div>
          <a-steps :current="current">
            <a-step v-for="item in steps" :key="item.title" :title="item.title">
              <a-icon slot="icon" :type="item.iconType" />
              <span style="color:#00DB00;" slot="description">{{item.description}}</span>
            </a-step>
          </a-steps>
          <div class="steps-content" style="" >
            <template   >
              <a-col :sm="12" v-show="current == 0" style="width:1000px">
                <label>
                  <a-tag color="#f50" style="font-weight: bold;font-size: 16px;margin-left: 110px">
                    入库类：
                  </a-tag>
                  <label style="font-weight: bold;font-size: 18px"><input type="radio" @change="onChangeType" name="type" value="1" v-model="type"> 公司采购</label>&nbsp;&nbsp;&nbsp;&nbsp;
                  <label style="font-weight: bold;font-size: 18px"><input type="radio" @change="onChangeType" name="type" value="2" v-model="type"> 客户来件</label>&nbsp;&nbsp;&nbsp;&nbsp;
                  <label style="font-weight: bold;font-size: 18px"><input type="radio" @change="onChangeType" name="type" value="6" v-model="type"> 内部收件</label>
                  <br/>
                  <a-tag color="#2db7f5" style="font-weight: bold;font-size: 16px;margin-left: 75px">
                    出库类：
                  </a-tag>
                  <label style="font-weight: bold;font-size: 18px"><input type="radio" @change="onChangeType" name="type" value="3" v-model="type"> 退购件</label>&nbsp;&nbsp;&nbsp;&nbsp;
                  <label style="font-weight: bold;font-size: 18px"><input type="radio" @change="onChangeType" name="type" value="4" v-model="type"> 退客件</label>&nbsp;&nbsp;&nbsp;&nbsp;
                  <label style="font-weight: bold;font-size: 18px"><input type="radio" @change="onChangeType" name="type" value="5" v-model="type"> 内部发件</label>
                  <br/>
                  <a-tag color="#87d068" style="font-weight: bold;font-size: 16px;margin-left: -145px">
                    其他类：
                  </a-tag>
                  <label style="font-weight: bold;font-size: 18px"><input type="radio" @change="onChangeType" name="type" value="7" v-model="type"> 调仓</label>
                </label>
              </a-col>
            </template>
            <template>
              <a-col v-show="current == 1 && (this.type == 1 || this.type == 2)" style="padding-left: 200px;padding-top: 60px;">
                <a-form-model-item label="发出客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sendCustomer">
                  <j-dict-select-tag ref="sendCustomer" style="width: 300px;margin-left: -300px;font-size:16px"  @change="onChangeSendInfo(3)" v-model="sendCustomer" placeholder="请选择发出客户" dictCode="customer_info,cus_name,id"/>
                </a-form-model-item>
              </a-col>
              <a-col v-show="current == 1 && this.type == 6" style="padding-left: 200px;padding-top: 60px">
                <a-form-model-item label="发出员工"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sendPerson">
                  <j-select-user-by-dep @change="onChangeSendInfo(1)"  style="width: 200px;margin-left: 10px;" ref="sendPerson" placeholder="请选择发出员工" :multi="false" v-model="sendPerson"/>
                </a-form-model-item>
              </a-col>
              <a-col v-show="current == 1 && (this.type == 3 || this.type == 4 || this.type == 5 || this.type == 7)" style="padding-left: 100px;padding-top: 60px">
                <a-form-model-item label="发出仓库"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sendStorage">
                  <j-dict-select-tag @change="onChangeSendInfo(2)" ref="sendStorage" v-model="sendStorage"
                                     style="width: 300px;margin-left: -300px;" placeholder="请选择发出仓库" dictCode="accessory_storage,name,id"/>
                </a-form-model-item>
              </a-col>
            </template>
            <template >
              <a-col v-show="current == 2 && (this.type == 1 || this.type == 2 || this.type == 6 || this.type == 7)" style="padding-left: 100px;padding-top: 60px">
                <a-form-model-item label="接收仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receiveStorage">
                  <j-dict-select-tag @change="onChangeReceiveInfo(2)" ref="receiveStorage" v-model="receiveStorage" style="width: 300px;margin-left: -300px" placeholder="请选择接收仓库" dictCode="accessory_storage,name,id"/>
                </a-form-model-item>
              </a-col>

              <a-col v-show="current == 2 && (this.type == 3 || this.type == 4)">
                <a-form-model-item style="padding-left: 200px;padding-top: 40px" label="接收客户"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receiveCustomer">
                  <j-dict-select-tag ref="receiveCustomer" style="width: 300px;margin-left: -300px"  @change="onChangeReceiveInfo(3)" v-model="receiveCustomer" placeholder="请选择接收客户" dictCode="customer_info,cus_name,id"/>

                </a-form-model-item>
              </a-col>

              <a-col v-show="current == 2 && (this.type == 5)" style="padding-left: 200px;padding-top: 60px">
                <a-form-model-item label="接收员工"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivePerson">
                  <j-select-user-by-dep @change="onChangeReceiveInfo(1)" style="width: 200px;margin-left: 10px" placeholder="请选择接收员工" :multi="false" v-model="receivePerson"/>
                </a-form-model-item>
              </a-col>

            </template>
            <template >
              <div v-show="current == 3">
                <j-editable-table
                  ref="editableTable"
                  :loading="loading"
                  :columns="columns"
                  :dataSource="dataSource"
                  :rowNumber="true"
                  :rowSelection="showRowSelection"
                  :actionButton="showActionButton"
                  :dragSort="showDragSort"
                  :scroll="{x:true,y:true}"
                  style="margin: 2px 2px 3px 3px"
                  @valueChange="handleValueChange"
                  @selectRowChange="handleSelectRowChange">

                  <template v-slot:action="props">
                    <a @click="handleDelete(props)">删除</a>
                  </template>
                  <template v-slot:priceDate>
                    <a-date-picker />
                  </template>
                </j-editable-table>
              </div>

              <div>{{tips}}</div>
            </template>
          </div>
          <div class="steps-action">
            <a-button :disabled="current == 0" @click="prev">
              上一步
            </a-button>
            <a-button :disabled="current == (steps.length - 1)" ref="nextBtn" style="margin-left: 8px" type="primary" @click="next">
              下一步
            </a-button>
          </div>
        </div>
      </a-form-model>
    </a-spin>
  </j-modal>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { randomUUID } from '@/utils/util'
import JEditableTable from '@/components/jeecg/JEditableTable'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import JTreeSelect from '@/components/jeecg/JTreeSelect'


export default {
  components: { JEditableTable,JSelectDepart,JTreeSelect },
  data() {
    return {
      title: '配件出入库',
      width:1200,
      visible: false,
      confirmLoading: false,
      disableMixinCreated: false,//执行jeecg默认的created事件
      previewVisable: false,
      tips:'',
      form1: this.$form.createForm(this),
      current: 0,
      steps: [
        {
          title: '操作类型',
          content: 'First-content',
          iconType: 'appstore',
          description: ''
        },
        {
          title: '发出方',
          content: 'Second-content',
          iconType: 'user-delete',
          description: ''
        },
        {
          title: '接收方',
          content: 'Third-content',
          iconType: 'user-add',
          description: ''
        },
        {
          title: '确认',
          content: 'Fourth-content',
          iconType: 'form',
          description: ''
        }
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      showRowSelection: true,
      showActionButton: true,
      showDragSort: true,
      type: '',
      sendPerson: '',
      sendStorage: '',
      sendCustomer: '',
      receivePerson: '',
      receiveStorage: '',
      receiveCustomer: '',
      sendByName:'',//提示语
      receiveByName:'',//提示语
      loading: false,
      columns: [
        {
          title: '配件编号',
          key: 'codeNum',
          width: '120px',
          type: FormTypes.input,
        },{
          title: '配件名称',
          key: 'name',
          width: '160px',
          type: FormTypes.input,
        },
        {
          title: '工单号',
          key: 'workNum',
          width: '100px',
          type: FormTypes.input,
        },{
          title: '拆分页',
          key: 'pn',
          width: '70px',
          type: FormTypes.input,
        },{
          title: '款号',
          key: 'styleCodeNum',
          width: '120px',
          type: FormTypes.input,
        },{
          title: '成色',
          key: 'karat',
          width: '120px',
          type: FormTypes.select,
          dictCode:'gold_karat,gold_karat_name,id',
        },{
          title: '类别',
          key: 'cateId',
          width: '120px',
          type: FormTypes.select,
          dictCode:'accessory_category,cate_name,id'
        },{
          title: '规格',
          key: 'style',
          width: '100px',
          type: FormTypes.input,
        },{
          title: '计重方式',
          key: 'countWeightPattern',
          width: '120px',
          type: FormTypes.select,
          dictCode:'count_weight_pattern'
        },{
          title: '重量(g)',
          key: 'weight',
          width: '100px',
          type: FormTypes.input,
        },{
          title: '数量*',
          key: 'count',
          width: '100px',
          type: FormTypes.input,
        },{
          title: '计价方式',
          key: 'countPricePattern',
          width: '100px',
          type: FormTypes.select,
          dictCode: "count_price_pattern"
        },{
          title: '单价(￥)',
          key: 'price',
          width: '100px',
          type: FormTypes.input
        },{
          title: '实付金额(￥)',
          key: 'payAmount',
          width: '120px',
          type: FormTypes.input,
          disabled: true
        },{
          title: '单位',
          key: 'per',
          width: '100px',
          type: FormTypes.input
        },{
          title: '工费(￥)',
          key: 'laborCost',
          width: '100px',
          type: FormTypes.input,
        },{
          title: '价值单价(￥)',
          key: 'unitPrice',
          width: '120px',
          type: FormTypes.input,
        },{
          title: '价值金额(￥)',
          key: 'costAmount',
          width: '120px',
          type: FormTypes.input
        },{
          title: '计价日期',
          key: 'priceDate',
          width: '130px',
          type: FormTypes.input,
          //slotName: "priceDate"
        },{
          title: '颜色',
          key: 'color',
          width: '100px',
          type: FormTypes.select,
          dictCode: "color"
        },{
          title: '属性',
          key: 'attribute',
          width: '100px',
          type: FormTypes.input
        },{
          title: '形状',
          key: 'shape',
          width: '100px',
          type: FormTypes.select,
          dictCode: "shape"
        },{
          title: '长度',
          key: 'len',
          width: '100px',
          type: FormTypes.input
        },{
          title: '来源',
          key: 'comeFrom',
          width: '100px',
          type: FormTypes.input,
        },{
          title: '是否客来',
          key: 'isFromCus',
          width: '100px',
          type: FormTypes.select,
          dictCode: "yn"
        },{
          title: '备注',
          key: 'remark',
          width: '100px',
          type: FormTypes.input,
        },
      ],
      dataSource: [],
      selectedRowIds: [],
      url: {
        getPerson : "/accessoryEntry/getPerson",
        getStorage : "/accessoryEntry/getStorage",
        getCustomer : "/accessoryEntry/getCustomer"
      }
    };
  },
  computed: {

  },
  mounted() {

  },
  //自动触发点击事件
  watch:{
    type(newVal,oldVal){
      if(newVal !='' && newVal !== oldVal) {
        this.$refs.nextBtn.$emit('click')
      }
    },
    sendPerson(newVal,oldVal){
      if(newVal !='' && newVal !== oldVal) {
        this.$refs.nextBtn.$emit('click')
      }
    },
    sendCustomer(newVal,oldVal){
      if(newVal !='' && newVal !== oldVal) {
        this.$refs.nextBtn.$emit('click')
      }
    },
    sendStorage(newVal,oldVal){
      if(newVal !='' && newVal !== oldVal) {
        this.$refs.nextBtn.$emit('click')
      }
    },
    receivePerson(newVal,oldVal){
      if(newVal !='' && newVal !== oldVal) {
        this.$refs.nextBtn.$emit('click')
      }
    },
    receiveCustomer(newVal,oldVal){
      if(newVal !='' && newVal !== oldVal) {
        this.$refs.nextBtn.$emit('click')
      }
    },
    receiveStorage(newVal,oldVal){
      if(newVal !='' && newVal !== oldVal) {
        this.$refs.nextBtn.$emit('click')
      }
    }
  },
  methods: {
    initStorageData(url,params) {//初始化仓库库存数据
      this.showRowSelection = true
      this.showActionButton = false
      this.showDragSort = false
      let that = this
      getAction(url,params).then((res)=>{
        if(res.success){
          let size = res.result.length
          let values = []
          for (let i = 0; i < size; i++) {
            let idStr = randomUUID()
            values.push(
              {
                id: idStr,
                codeNum: '',
                workNum: '',
                pn: '',
                styleCodeNum: '',
                karat: res.result[i].karat,
                name: '',
                cateId: res.result[i].cateId,
                style: res.result[i].style,
                count: res.result[i].count,
                weight: res.result[i].weight,
                costAmount: res.result[i].costAmount,
                payAmount: res.result[i].payAmount,
                unitPrice: '',
                countPricePattern: '',
                countWeightPattern: '',
                priceDate: '',
                laborCost: '',
                color: '',
                attribute: '',
                shape: '',
                len: '',
                comeFrom: '',
                isFromCus: '',
                remark: ''
              }
            )
          }
          that.dataSource = values
        }else{
          that.$message.warning(res.message);
        }
      })
    },
    getFormFieldValue(field){
      return this.form1.getFieldValue(field)
    },
    next() {
      if(this.current == 0) {
        if(this.type == '') {
          this.$message.warning('请先选择操作类型！');
          return
        }
        this.current++;
      }
      if(this.current == "1") {//发出方
        if(this.type == 1 || this.type == 2){//发出方是客户
          if(this.sendCustomer == null || this.sendCustomer == ''){
            //this.$message.warning('请选择发出客户')
            return
          }
          this.current++;
        } else if (this.type == 6) {//发出方是员工
          if(this.sendPerson == null || this.sendPerson == ''){
            //this.$message.warning('请选择发出员工')
            return false
          }
          this.current++;
        } else if (this.type == 3 || this.type == 4 || this.type == 5 ||  this.type == 7) {//发出方是仓库
          if(this.sendStorage == null || this.sendStorage == ''){
            //this.$message.warning('请选择发出仓库')
            return
          }
          this.current++;
        }
      }else if(this.current == "2") {//接收方
        if (this.type == 1 || this.type == 2 || this.type == 6 || this.type == 7) {//接收仓库
          if(this.receiveStorage == null || this.receiveStorage == ''){
            //this.$message.warning('请选择接收仓库')
            return
          }
          this.current++;
        } else if (this.type == 3 || this.type == 4) {//接收客户
          if(this.receiveCustomer == null || this.receiveCustomer == ''){
            //this.$message.warning('请选择接收客户')
            return
          }
          this.current++;
        } else if (this.type == 5) {//接收员工
          if(this.receivePerson == null || this.receivePerson == ''){
            //this.$message.warning('请选择接收员工')
            return
          }
          this.current++;
        }
      }
      if(this.current == "3") {//确认
        if(this.type == 3 || this.type == 4 || this.type == 5 || this.type == 7){//库存在仓库
          let params = {
            storageId: this.sendStorage
          }
          this.initStorageData("/accessoryEntry/queryStorageData",params)
        } else if(this.type == 6){//库存在员工
          let params = {
            userId: this.sendPerson
          }
          this.initStorageData("/accessoryEntry/queryPersonData",params)
        }
      }
    },
    prev() {
      this.current--;
    },
    init () {
      this.visible = true
    },
    handleValueChange(event) {
      const { type, row, column, value, target } = event
      if (type === FormTypes.input) {
        if (column.key == 'codeNum') {
          target.setValues([{
            rowKey: row.id,
            values: { codeNum: value}
          }])
          if(value != null && value != '' && value.length >= 4){
            let params = {
              codeNum : value
            }
            getAction("/accessoryEntry/queryAccessoryInfoByCodeNum",params).then(res=>{
              if(res.success){
                target.setValues([{
                  rowKey: row.id,
                  values: { codeNum: res.result.code_num}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { name: res.result.name}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { cateId: res.result.cate_id}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { style: res.result.style}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { per: res.result.per}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { price: res.result.price}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { weight: res.result.weight}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { countPricePattern: res.result.count_price_pattern}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { countWeightPattern: res.result.count_weight_pattern}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { color: res.result.color}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { karat: res.result.karat}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { comeFrom: res.result.come_from}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { attribute: res.result.attribute}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { shape: res.result.shape}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { len: res.result.len}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { priceDate: res.result.price_date}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { isFromCus: res.result.is_from_cus}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { customerInfoId: res.result.customer}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { laborCost: res.result.labor_cost}
                }])
                target.setValues([{
                  rowKey: row.id,
                  values: { remark: res.result.mark}
                }])
              }
            })
          }
        } else if (column.key == 'count') {
          target.setValues([{
            rowKey: row.id,
            values: { count: value}
          }])
        } else if (column.key == 'weight') {
          target.setValues([{
            rowKey: row.id,
            values: { weight: value}
          }])
        } else if (column.key == 'price') {
          target.setValues([{
            rowKey: row.id,
            values: { price: value}
          }])
        } else {
          return
        }
      } else if (type === FormTypes.select) {
        if (column.key == 'countPricePattern') {
          target.setValues([{
            rowKey: row.id,
            values: { countPricePattern: value}
          }])
        } else {
          return
        }
      }
      let payAmountVal = 0
      if(row.countPricePattern == '1') {//按重
        payAmountVal = (row.price * row.weight).toFixed(2)
      } else if(row.countPricePattern == '3') {//按件
        payAmountVal = (row.price * row.count).toFixed(2)
      }
      target.setValues([{
        rowKey: row.id,
        values: { payAmount: payAmountVal }
      }])
    },
    onChangeSendInfo(type) {
      if(type == 1){//发出类型是员工
        if(this.sendPerson == ''){
          this.steps[this.current].description = ''
          return
        }
        let params = {
          username: this.sendPerson
        }
        getAction(this.url.getPerson,params).then((res)=>{
          if(res.success){
            this.steps[this.current - 1].description = res.result
          }
        })
      } else if (type == 2) {//发出类型是仓库
        if(this.sendStorage == ''){
          this.steps[this.current].description = ''
          return
        }
        let params = {
          id: this.sendStorage
        }
        getAction(this.url.getStorage,params).then((res)=>{
          if(res.success){
            this.steps[this.current - 1].description = res.result
          }
        })
      } else if (type == 3) {//发出类型是客户
        if(this.sendCustomer == ''){
          this.steps[this.current].description = ''
          return
        }
        let params = {
          id: this.sendCustomer
        }
        getAction(this.url.getCustomer,params).then((res)=>{
          if(res.success){
            this.steps[this.current - 1].description = res.result
          }
        })
      }
    },
    onChangeReceiveInfo(type) {
      if(type == 1){//接收类型是员工
        if(this.receivePerson == ''){
          this.steps[this.current].description = ''
          return
        }
        let params = {
          username: this.receivePerson
        }
        getAction(this.url.getPerson,params).then((res)=>{
          if(res.success){
            this.steps[this.current - 1].description = res.result
          }
        })
      } else if (type == 2) {//接收类型是仓库
        if(this.receiveStorage == ''){
          this.steps[this.current].description = ''
          return
        }
        let params = {
          id: this.receiveStorage
        }
        getAction(this.url.getStorage,params).then((res)=>{
          if(res.success){
            this.steps[this.current - 1].description = res.result
          }
        })
      } else if (type == 3) {//接收类型是客户
        if(this.receiveCustomer == ''){
          this.steps[this.current].description = ''
          return
        }
        let params = {
          id: this.receiveCustomer
        }
        getAction(this.url.getCustomer,params).then((res)=>{
          if(res.success){
            this.steps[this.current - 1].description = res.result
          }
        })
      }
    },
    onChangeType () {
      this.showActionButton = true
      this.steps[1].description = ''
      this.steps[2].description = ''
      this.sendPerson = ''
      this.sendStorage = ''
      this.sendCustomer = ''
      this.receivePerson = ''
      this.receiveStorage = ''
      if(this.type == 1) {//公司采购
        this.steps[0].description = '公司采购'
      } else if(this.type == 2) {//客户来件
        this.steps[0].description = '客户来件'
      } else if(this.type == 3) {//退购件
        this.steps[0].description = '退购件'
      } else if(this.type == 4) {//退客件
        this.steps[0].description = '退客件'
      } else if(this.type == 5) {//内部发件
        this.steps[0].description = '内部发件'
      } else if(this.type == 6) {//内部收件
        this.steps[0].description = '内部收件'
      } else if(this.type == 7) {//调仓
        this.steps[0].description = '调仓'
      }
    },
    close () {
      this.confirmLoading = false;
      this.$emit('ok')
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      Object.assign(this.$data, this.$options.data.call(this))
      this.visible = false
    },
    handleOk () {
      const that = this
      this.handleTableGet()
    },
    handleClose () {
      this.close()
    },
    /** 表单验证 */
    handleTableCheck() {
      this.$refs.editableTable.getValues((error) => {
        if (error === 0) {
          this.$message.success('验证通过')
        } else {
          this.$message.error('验证未通过')
        }
      })
    },
    /** 获取值，忽略表单验证 */
    handleTableGet() {
      this.$refs.editableTable.getValues((error, values) => {
        let params = {
          sendPerson: this.sendPerson,
          sendStorage: this.sendStorage,
          sendCustomer: this.sendCustomer,
          receivePerson: this.receivePerson,
          receiveStorage: this.receiveStorage,
          receiveCustomer: this.receiveCustomer,
          type: this.type,
          data : values
        }
        postAction("/accessoryEntry/batchAdd",params).then(res=>{
          if(res.success){
            this.$message.success(res.message)
            this.close()
          }else{
            this.$message.error(res.message)
          }
        })
      }, false, this.selectedRowIds)
    },
    handleSelectRowChange(selectedRowIds) {
      this.selectedRowIds = selectedRowIds
    },
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    handleCancel(id) {
      this.$refs[id].previewVisible = false;
    },
    handlePreview(id) {
      this.$refs[id].previewVisible = true;
    },
  },
};
</script>
<style scoped>
.steps-content {
  margin-top: 16px;
  border: 1px dashed #aaaaaa;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 300px;
  text-align: center;
  padding-top: 20px;
}

.steps-action {
  margin-top: 24px;
}
</style>